package com.atguigu.day08;

import com.atguigu.util.Event;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

public class Example5 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // flink cep 必须使用事件时间
        var stream = env
                .addSource(new SourceFunction<Event>() {
                    @Override
                    public void run(SourceContext<Event> ctx) {
                        ctx.collectWithTimestamp(new Event("user-1", "login-fail", 1000L), 1000L);
                        ctx.collectWithTimestamp(new Event("user-1", "login-fail", 2000L), 2000L);
                        ctx.collectWithTimestamp(new Event("user-2", "login-success", 3000L), 3000L);
                        ctx.collectWithTimestamp(new Event("user-1", "login-fail", 4000L), 4000L);
                        ctx.collectWithTimestamp(new Event("user-1", "login-fail", 5000L), 5000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        // 定义模板
        var pattern = Pattern
                .<Event>begin("fail")
                .where(new SimpleCondition<>() {
                    @Override
                    public boolean filter(Event value) {
                        return value.type.equals("login-fail");
                    }
                })
                // 出现三次
                .times(3)
                // 要求事件连续出现
                .consecutive();

        // 在数据流上检测符合模板的事件组，然后提取出来并打印
        CEP
                .pattern(stream.keyBy(r -> r.key), pattern)
                // 泛型：事件组中的事件类型，输出的类型
                .select(map -> {
                    // map参数的结构：{
                    //    "fail": [Event, Event, Event]
                    // }
                    var first = map.get("fail").get(0);
                    var second = map.get("fail").get(1);
                    var third = map.get("fail").get(2);

                    return first.key + "连续三次登陆失败，登陆时间是：" + first.ts + "; " + second.ts + "; " + third.ts;
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
